<?php

namespace app\api\controller;

use app\admin\model\Lostandfound;
use app\common\controller\Api;
use think\exception\DbException;
use think\Paginator;

/**
 * 寻人寻物
 */
class Lost extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = '*';

    /**
     * 发布帖子
     * @return void
     */
    public function publish()
    {

        $params = input();
        $validate = $this->validate($params, [
            'title|标题必填' => 'require|max:255',
            'type|类型' => 'require|in:1,2',
            'name|联系人' => 'require|max:32',
            'phone|电话' => 'require|max:16'
        ]);
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$params['phone'] || !\think\Validate::regex($params['phone'], "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $params['user_id'] = $this->getUserId();
        try {
            Lostandfound::create($params, true);
        } catch (\Exception $e) {
            $this->error("发布失败" . $e->getMessage());
        }
        $this->success("发布成功");
    }

    /**
     * 帖子列表
     * @return void
     * @throws DbException
     */
    public function list()
    {
        $type = input('type');
        $page = input('page', 1);
        $where = [];
        if (!empty($type)) {
            $where['type'] = ['=', $type];
        }
        $list = Lostandfound::where($where)->with(['user' => function ($query) {
            $query->field('id,username,nickname,avatar');
        }])->order('id', 'desc')->paginate($page);
        $this->paginate($list);
    }
}